package com.zlf.file.tika;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;

import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.mp3.LyricsHandler;
import org.apache.tika.parser.mp3.Mp3Parser;
import org.apache.tika.sax.BodyContentHandler;

import org.junit.Test;
import org.xml.sax.SAXException;

/**
 * 不能设置原数据
 */
public class Mp3Parse {

    public static void main(final String[] args) throws Exception, IOException, SAXException, TikaException {

        //detecting the file type
        BodyContentHandler handler = new BodyContentHandler();
        Metadata metadata = new Metadata();
        FileInputStream inputstream = new FileInputStream(new File("/home/zlf/Music/海鸣威 - 老人与海.mp3"));
        ParseContext pcontext = new ParseContext();

        //Mp3 parser
        Mp3Parser  Mp3Parser = new  Mp3Parser();
        Mp3Parser.parse(inputstream, handler, metadata, pcontext);
        LyricsHandler lyrics = new LyricsHandler(inputstream,handler);

        while(lyrics.hasLyrics()) {
            System.out.println(lyrics.toString());
        }

        System.out.println("Contents of the document:" + handler.toString());
        System.out.println("Metadata of the document:");
        String[] metadataNames = metadata.names();
        System.out.println("===="+metadataNames.length);
        for(String name : metadataNames) {
            System.out.println(name + ": " + metadata.get(name));
        }
    }

    @Test
    public void testMetadata() throws IOException, TikaException, SAXException {
        BodyContentHandler handler = new BodyContentHandler();
        Metadata metadata = new Metadata();
        FileInputStream inputstream = new FileInputStream(new File("/home/zlf/Music/龙猫组合 - 爱情专属权.mp3 "));
        ParseContext pcontext = new ParseContext();

        //Mp3 parser
        Mp3Parser  Mp3Parser = new  Mp3Parser();
        Mp3Parser.parse(inputstream, handler, metadata, pcontext);

        metadata.set("createDate",new Date().toString());
        metadata.set(Metadata.DATE, new Date());


        String[] metadataNames = metadata.names();
        System.out.println("===="+metadataNames.length);
        for(String name : metadataNames) {
            System.out.println(name + ": " + metadata.get(name));
        }
        inputstream.close();
    }

}